package com.dji.sdk.self.internal.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.dji.sdk.self.internal.model.LoginUser;
import com.dji.sdk.self.internal.network.RetrofitUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;

public class LoginUtils {
    private Context mContext;
    private String name,token,url;
    //freshTokenAt超过时长重新登录，accessTokenAt超过时长刷新token
    private long accessTokenAt,freshTokenAt,now;
    private SharedPreferences loginPreferences,urlPreferences;
    private boolean isLogin = false;

    public interface Callback{
        void onDataChange(String pushUrl);
    }
    private Callback callback = null;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }


    public LoginUtils(Context context){
        mContext = context;
        loginPreferences = mContext.getSharedPreferences("LoginToken",0);
        urlPreferences = mContext.getSharedPreferences("LiveStreamUrl",0);
        name = loginPreferences.getString("username",null);
        token = loginPreferences.getString("loginToken",null);
        accessTokenAt = loginPreferences.getLong("accessTokenExpiresAt",0);
        freshTokenAt = loginPreferences.getLong("refreshTokenExpiresAt",0);
        now = System.currentTimeMillis();

    }
    public boolean login(String username,String pwd){
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser.setPassword(pwd);
        loginUser.setRememberme(0);
        RetrofitUtil.getInstance().getApi()
                .login(loginUser)
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        SharedPreferences.Editor editor = loginPreferences.edit();
                        String responseJSON = null;
                        try {
                            responseJSON = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.i("SendHttp",responseJSON);
                        Gson result = new Gson();
                        Map dataMapper = result.fromJson(responseJSON,Map.class);
                        Log.i("SendHttp", (String) dataMapper.get("token"));
                        if(response.isSuccessful()){
                            ToastUtils.setResultToToast("data is successful");
                            String tempToken =(String) dataMapper.get("token");
                            Log.i("LoginActivity",tempToken);
                            if(!TextUtils.isEmpty(tempToken)){
                                token = tempToken;
                                // ToastUtils.setResultToToast("token:"+token);
                                editor.putString("loginToken",token);
                                Log.i("LOGINACTIVITY full",dataMapper.toString());
                                isLogin = true;
                                editor.putString("username",name);
                                editor.putString("password",pwd);
                                editor.putLong("refreshTokenExpiresAt", 86400 * 1000 + now);
                                editor.putLong("accessTokenExpiresAt", 9000 * 1000 + now);
                                editor.putString("login","true");
                                editor.apply();
                            }else{
                                ToastUtils.setResultToToast((String)dataMapper.get("msg"));
                            }

                        }else if(!response.isSuccessful()){

                            String message = (String) dataMapper.get("title");
                            if (message!=null&&message.equals("userName is not exist")){
                                ToastUtils.setResultToToast("当前用户不存在，请检查用户名和密码是否输入正确！");
                            }
                            int attempts = (int) dataMapper.get("attempts");
                            String msg = (String) dataMapper.get("msg");
                            long lockTime = (long) dataMapper.get("lockoutTime");
                            if(attempts>0&&lockTime==0){
                                ToastUtils.setResultToToast("请检查密码是否正确，您还有"+attempts+"次尝试机会！");
                            }
                            if(lockTime>0){
                                long time = lockTime/60;
                                ToastUtils.setResultToToast("由于密码输入错误，该账户已被锁，请在"+time+"分钟后重新尝试！");
                            }
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                        ToastUtils.setResultToToast("请求失败"+t.getMessage());
                    }
                });


        return isLogin;
    }
    public boolean logout(){
        SharedPreferences.Editor editor = loginPreferences.edit();
        editor.putString("loginToken",null)
                .putString("login",null)
                .putLong("refreshTokenExpiresAt",0)
                .putLong("accessTokenExpiresAt",0)
                .apply();
        return false;
    }
    public String isLogin(){
        if(token==null||name==null||now>freshTokenAt){
            isLogin = false;
            name = null;
        }else{
            isLogin = true;
        }
        return name;
    }

    public String getUrl(String serialNumber){
        if(!TextUtils.isEmpty(serialNumber)){
            RetrofitUtil.getInstance().getApi().getLiveStreamUrl(serialNumber,token)
                    .enqueue(new retrofit2.Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                            try {
                                url = response.body().string();
                                urlPreferences.edit()
                                        .putString("liveUrl",url)
                                        .putString("serialNumber",serialNumber)
                                        .apply();
                                callback.onDataChange(url);
                                Log.i("GetUrl",url);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
        }
        return url;
    }

    public void refreshToken() throws IOException {

        RetrofitUtil.getInstance().getApi()
                .getFreshToken(0,token)
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        try {
                            String res = response.body().string();
                            Log.i("SendHttp",res);
                            Gson gson = new Gson();
                            Map result = gson.fromJson(res, Map.class);
                            String newAccessToken = (String) result.get("token");
                            // 因为发生了请求，当前时间已经变化，所有重新获取时间
                            long now2 = System.currentTimeMillis();
                            // 保存到 SharedPreferences
                            loginPreferences.edit()
                                    .putString("loginToken", newAccessToken)
                                    .putLong("refreshTokenExpiresAt", 86400 * 1000 + now2)
                                    .putLong("accessTokenExpiresAt", 9000 * 1000 + now2)
                                    .apply();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

                    }
                });
    }

}
